/////////////////////////////////////////////////////////////////////////////
// Name:        sql-ledgerpointofsale.cpp
// Purpose:     
// Author:      Herry Sugiharto
// Modified by: 
// Created:     07/09/2008 00:46:39
// RCS-ID:      
// Copyright:   Copyright (c) 2000, 2008 Krida Software Division
// Licence:     
/////////////////////////////////////////////////////////////////////////////

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
#pragma hdrstop
#endif

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

////@begin includes
#include "listctrlItem.h"
#include "payment.h"
////@end includes
#include "setting.h"

#include "sql-ledgerpointofsale.h"

////@begin XPM images
////@end XPM images


/*!
 * SLPointofSale type definition
 */

IMPLEMENT_DYNAMIC_CLASS( SLPointofSale, wxDialog )


/*!
 * SLPointofSale event table definition
 */

BEGIN_EVENT_TABLE( SLPointofSale, wxDialog )

////@begin SLPointofSale event table entries
    EVT_TEXT_ENTER( ID_TEXT_SCAN, SLPointofSale::OnTextScanEnter )

////@end SLPointofSale event table entries

END_EVENT_TABLE()


/*!
 * SLPointofSale constructors
 */

SLPointofSale::SLPointofSale()
{
    Init();
}

SLPointofSale::SLPointofSale( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
    Init();
    Create(parent, id, caption, pos, size, style);
}


/*!
 * SLPointofSale creator
 */

bool SLPointofSale::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
////@begin SLPointofSale creation
    SetExtraStyle(wxWS_EX_BLOCK_EVENTS);
    wxDialog::Create( parent, id, caption, pos, size, style );

    CreateControls();
    if (GetSizer())
    {
        GetSizer()->SetSizeHints(this);
    }
    Centre();
////@end SLPointofSale creation
    return true;
}


/*!
 * SLPointofSale destructor
 */

SLPointofSale::~SLPointofSale()
{
////@begin SLPointofSale destruction
////@end SLPointofSale destruction
    delete cashierdata;
}


/*!
 * Member initialisation
 */

void SLPointofSale::Init()
{
////@begin SLPointofSale member initialisation
    quantity = wxT("1");
    grandtotal = 0;
    discount = wxT("0");
////@end SLPointofSale member initialisation
    cashierdata = new CashierData(wxGetApp().conn);
    wxGetApp().printer = new wxHtmlEasyPrinting();
    long MarTop, MarLeft;
    wxGetApp().MarginTop.ToLong(&MarTop);
    wxGetApp().MarginLeft.ToLong(&MarLeft);
    wxGetApp().printer->GetPageSetupData()->SetMarginTopLeft(wxPoint(MarTop, MarLeft));
}


/*!
 * Control creation for SLPointofSale
 */

void SLPointofSale::CreateControls()
{    
////@begin SLPointofSale content construction
    SLPointofSale* itemDialog1 = this;

    wxBoxSizer* itemBoxSizer2 = new wxBoxSizer(wxVERTICAL);
    itemDialog1->SetSizer(itemBoxSizer2);

    wxTextCtrl* itemTextCtrl3 = new wxTextCtrl( itemDialog1, ID_GRANDTOTAL, _("0"), wxDefaultPosition, wxDefaultSize, wxTE_READONLY|wxTE_RIGHT|wxNO_BORDER );
    itemTextCtrl3->SetFont(wxFont(36, wxSWISS, wxNORMAL, wxNORMAL, false, wxT("Tahoma")));
    itemTextCtrl3->Enable(false);
    itemBoxSizer2->Add(itemTextCtrl3, 0, wxGROW|wxALL, 5);

    listctrlItem* itemListCtrl4 = new listctrlItem( itemDialog1, ID_LISTCTRL, wxDefaultPosition, wxSize(720, 400), wxLC_REPORT|wxLC_SINGLE_SEL );
    itemListCtrl4->Enable(false);
    itemBoxSizer2->Add(itemListCtrl4, 1, wxGROW|wxALL, 5);

    wxBoxSizer* itemBoxSizer5 = new wxBoxSizer(wxHORIZONTAL);
    itemBoxSizer2->Add(itemBoxSizer5, 0, wxGROW|wxLEFT|wxRIGHT, 5);

    wxStaticText* itemStaticText6 = new wxStaticText( itemDialog1, wxID_STATIC, _("Scan:"), wxDefaultPosition, wxDefaultSize, 0 );
    itemBoxSizer5->Add(itemStaticText6, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);

    wxTextCtrl* itemTextCtrl7 = new wxTextCtrl( itemDialog1, ID_TEXT_SCAN, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER );
    itemTextCtrl7->SetFont(wxFont(20, wxSWISS, wxNORMAL, wxNORMAL, false, wxT("")));
    itemBoxSizer5->Add(itemTextCtrl7, 1, wxALIGN_CENTER_VERTICAL|wxALL, 5);

    wxBoxSizer* itemBoxSizer8 = new wxBoxSizer(wxVERTICAL);
    itemBoxSizer5->Add(itemBoxSizer8, 0, wxALIGN_CENTER_VERTICAL, 5);

    wxBoxSizer* itemBoxSizer9 = new wxBoxSizer(wxHORIZONTAL);
    itemBoxSizer8->Add(itemBoxSizer9, 0, wxGROW|wxLEFT, 5);

    wxStaticText* itemStaticText10 = new wxStaticText( itemDialog1, ID_STATIC_DISCOUNT, _("0"), wxDefaultPosition, wxDefaultSize, 0 );
    itemStaticText10->SetFont(wxFont(12, wxSWISS, wxNORMAL, wxNORMAL, false, wxT("Arial")));
    itemBoxSizer9->Add(itemStaticText10, 1, wxALIGN_CENTER_VERTICAL|wxLEFT|wxTOP|wxBOTTOM, 5);

    wxStaticText* itemStaticText11 = new wxStaticText( itemDialog1, ID_STATIC_PERCENT, _("%"), wxDefaultPosition, wxDefaultSize, 0 );
    itemStaticText11->SetFont(wxFont(10, wxSWISS, wxNORMAL, wxNORMAL, false, wxT("Arial")));
    itemBoxSizer9->Add(itemStaticText11, 0, wxALIGN_CENTER_VERTICAL|wxRIGHT, 5);

    wxBoxSizer* itemBoxSizer12 = new wxBoxSizer(wxHORIZONTAL);
    itemBoxSizer8->Add(itemBoxSizer12, 0, wxGROW|wxLEFT, 5);

    wxStaticText* itemStaticText13 = new wxStaticText( itemDialog1, ID_STATIC_X, _("x"), wxDefaultPosition, wxDefaultSize, 0 );
    itemStaticText13->SetFont(wxFont(12, wxSWISS, wxNORMAL, wxNORMAL, false, wxT("")));
    itemBoxSizer12->Add(itemStaticText13, 0, wxALIGN_CENTER_VERTICAL|wxLEFT|wxTOP|wxBOTTOM, 5);

    wxStaticText* itemStaticText14 = new wxStaticText( itemDialog1, ID_STATIC_QTY, _("1"), wxDefaultPosition, wxDefaultSize, 0 );
    itemStaticText14->SetFont(wxFont(12, wxSWISS, wxNORMAL, wxNORMAL, false, wxT("")));
    itemBoxSizer12->Add(itemStaticText14, 1, wxALIGN_CENTER_VERTICAL|wxRIGHT|wxTOP|wxBOTTOM, 5);

    wxStatusBar* itemStatusBar15 = new wxStatusBar( itemDialog1, ID_STATUSBAR, wxNO_BORDER );
    itemStatusBar15->SetFieldsCount(9);
    itemStatusBar15->SetStatusText(_("F1  Help"), 0);
    itemStatusBar15->SetStatusText(_("F2  Quantity"), 1);
    itemStatusBar15->SetStatusText(_("F3  Discount"), 2);
    itemStatusBar15->SetStatusText(_("F4  Lookup"), 3);
    itemStatusBar15->SetStatusText(_("F5  Cash"), 4);
    itemStatusBar15->SetStatusText(_("F6  Debit/Card"), 5);
    itemStatusBar15->SetStatusText(_("F7  Reset"), 6);
    itemStatusBar15->SetStatusText(_("F11  Settings"), 7);
    itemStatusBar15->SetStatusText(_("F12  Exit"), 8);
    itemBoxSizer2->Add(itemStatusBar15, 0, wxGROW|wxALL, 5);

    // Set validators
    itemTextCtrl7->SetValidator( wxTextValidator(wxFILTER_NONE, & ScannedText) );
    itemStaticText10->SetValidator( wxGenericValidator(& discount) );
    itemStaticText14->SetValidator( wxGenericValidator(& quantity) );
    // Connect events and objects
    itemTextCtrl7->Connect(ID_TEXT_SCAN, wxEVT_KEY_DOWN, wxKeyEventHandler(SLPointofSale::OnKeyDown), NULL, this);
////@end SLPointofSale content construction    
    itemTextCtrl7->SetFocus();
}


/*!
 * Should we show tooltips?
 */

bool SLPointofSale::ShowToolTips()
{
    return true;
}


/*!
 * Get bitmap resources
 */

wxBitmap SLPointofSale::GetBitmapResource( const wxString& name )
{
    // Bitmap retrieval
////@begin SLPointofSale bitmap retrieval
    wxUnusedVar(name);
    return wxNullBitmap;
////@end SLPointofSale bitmap retrieval
}


/*!
 * Get icon resources
 */

wxIcon SLPointofSale::GetIconResource( const wxString& name )
{
    // Icon retrieval
////@begin SLPointofSale icon retrieval
    wxUnusedVar(name);
    return wxNullIcon;
////@end SLPointofSale icon retrieval
}


/*!
 * wxEVT_COMMAND_TEXT_ENTER event handler for ID_TEXT_SCAN
 */

void SLPointofSale::OnTextScanEnter( wxCommandEvent& event )
{
    // find the corresponding controls
    listctrlItem *ctrl = (listctrlItem*) FindWindow(ID_LISTCTRL);
    wxTextCtrl *stext = (wxTextCtrl*) FindWindow(ID_GRANDTOTAL);

    wxString scantext = event.GetString();
    // add the entered item to the list
    ctrl->AddToList(scantext, quantity, discount);
    quantity = wxT("1");
    discount = wxT("0");

    // recalculate the grand total
    //grandtotal = cashierdata->GetGrandTotal(ctrl);
    grandtotal = ctrl->GetGrandTotal();

    // update the UI total
    wxString temp;
    temp << grandtotal;
    stext->SetValue(temp);

    // clear the text on the scanned textctrl
    ScannedText.Empty();
    TransferDataToWindow();
}


/*!
 * wxEVT_KEY_DOWN event handler for ID_SLPOINTOFSALE
 */

void SLPointofSale::OnKeyDown( wxKeyEvent& event )
{
    switch ( event.GetKeyCode() )
    {
        case (WXK_MULTIPLY):
        case (WXK_NUMPAD_MULTIPLY):
        case (WXK_F2): {
            wxTextCtrl *ctrl = (wxTextCtrl*) FindWindow(ID_TEXT_SCAN);
            wxString scantext = ctrl->GetValue();
            if ( scantext.IsNumber() && !scantext.IsEmpty() ) {
                quantity = scantext;
                TransferDataToWindow();
            };
            ctrl->SetValue("");
        };
        break;
        
        case (WXK_DIVIDE):
        case (WXK_NUMPAD_DIVIDE):
        case (WXK_F3): {
            wxTextCtrl *ctrl = (wxTextCtrl*) FindWindow(ID_TEXT_SCAN);
            wxString scantext = ctrl->GetValue();
            if ( scantext.IsNumber() && !scantext.IsEmpty() ) {
                discount = scantext;
                TransferDataToWindow();
            };
            ctrl->SetValue("");
        };
        break;
        
        case (WXK_F5): {
            
            listctrlItem *ctrl = (listctrlItem*) FindWindow(ID_LISTCTRL);
            if (ctrl->GetItemCount() == 0)
                break;
            
            Payment* window = new Payment(this);
            window->SetGrandTotal(grandtotal);
            int returnValue = window->ShowModal();
            
            if (returnValue == wxID_OK) {
                
                // get the user's entered payment amount
                long paymentamount = window->GetPaymentAmount();
                long change = window->GetChange();
                
                if ( !cashierdata->SaveOrder(wxDateTime::Now(), TRUE, ctrl) ) {
                    wxLogError(cashierdata->GetLastError());
                    break;
                } else {
                    wxString receipt = cashierdata->CreatePrintReceipt(wxDateTime::Now(), ctrl, paymentamount, TRUE);
                    wxGetApp().printer->PrintText(receipt);
                    // show the Change amount and thanks the customer
                    wxString dlgtext = _("Change: ");
                    dlgtext << change;
                    wxMessageBox(dlgtext, _("Thank You"));
                };
                ResetView();
            };
            window->Destroy();
        };
        break;

        case (WXK_F6): {
            
            listctrlItem *ctrl = (listctrlItem*) FindWindow(ID_LISTCTRL);
            if (ctrl->GetItemCount() == 0)
                break;
            
            Payment* window = new Payment(this);
            window->SetGrandTotal(grandtotal);
            window->SetPaymentAmount(grandtotal);
            int returnValue = window->ShowModal();
            
            if (returnValue == wxID_OK) {
                
                // get the user's entered payment amount
                long paymentamount = window->GetPaymentAmount();
                
                if ( !cashierdata->SaveOrder(wxDateTime::Now(), FALSE, ctrl) ) {
                    wxLogError(cashierdata->GetLastError());
                    break;
                } else {
                    wxString receipt = cashierdata->CreatePrintReceipt(wxDateTime::Now(), ctrl, paymentamount, FALSE);
                    wxGetApp().printer->PrintText(receipt);
                    wxMessageBox(_("Thank You"), _("Thank You"));
                };
                ResetView();
            };
            window->Destroy();
        };
        break;

        case (WXK_F7): {
            
            listctrlItem *ctrl = (listctrlItem*) FindWindow(ID_LISTCTRL);
            if (ctrl->GetItemCount() == 0)
                break;
                
            int answer = wxMessageBox(_("Erase all item in the list?"), _("Erase"), wxYES_NO | wxICON_QUESTION);
            if (answer == wxYES)
                ResetView();
        };
        break;
        
        case (WXK_F11): {
            Setting* window = new Setting(this);
            window->ShowModal();
            window->Destroy();
        };
        break;

        case (WXK_F12): {
            int answer = wxMessageBox(_("Quit program?"), _("Confirm"), wxYES_NO | wxICON_QUESTION);
            if (answer == wxYES) {
                wxDialog* dialog = wxDynamicCast(this, wxDialog);
                dialog->EndModal(ID_SLPOINTOFSALE);
            };
        };
        break;

        default:
            event.Skip();
    };
}


void SLPointofSale::ResetView()
{
    // find the corresponding controls
    listctrlItem *ctrl = (listctrlItem*) FindWindow(ID_LISTCTRL);
    wxTextCtrl *stext = (wxTextCtrl*) FindWindow(ID_GRANDTOTAL);
    
    ctrl->DeleteAllItems();
    stext->SetValue("0");
}
